import { ref, nextTick } from 'vue'
import type { MsgData } from '@/types/userInfo'
import { getMainPostApi, publishMsg } from '@/api/user'
import { useUserInfoStore } from '@/stores'
import { ImageAddHttp, formatTimestamp } from '@/utils/index'
import { onLoad } from '@dcloudio/uni-app'

export function useScript() {
  const mainPost = ref<MsgData>({
    id: 0,
    avatar: '',
    nickname: '',
    username: '',
    createtime: '',
    content: '',
  })
  const userInfo = ref(useUserInfoStore().$state.profile)
  const content = ref<string>('')
  const id = ref<number>(0)

  async function goBack() {
    uni.navigateBack()
  }

  async function getMainPost(id: number) {
    const result = await getMainPostApi(id)
    if (result.code) {
      mainPost.value = {
        id: result.data.id,
        avatar: ImageAddHttp(result.data.user.avatar),
        nickname: result.data.user.nickname,
        username: `@${result.data.user.username}`,
        createtime: formatTimestamp(result.data.createtime, 'yyyy-MM-dd HH:mm:ss'),
        content: result.data.content,
      }
    }
  }

  async function reply() {
    uni.showToast({
      title: '回复中...',
      icon: 'loading',
    })
    const result = await publishMsg({
      content: content.value,
      parent_id: mainPost.value.id,
    })

    if (result.code) {
      uni.navigateBack()
    } else {
      uni.showToast({
        title: '回复失败',
        icon: 'none',
      })
    }

    uni.hideToast()
  }

  onLoad(async (options) => {
    await nextTick()
    if (options && options.id) {
      id.value = options.id
      await getMainPost(options.id)
    }
  })

  return {
    userInfo,
    mainPost,
    content,
    goBack,
    reply,
  }
}
